<?php
namespace AliPay;

/**
 *
 * @author lovebing <i@lovebing.org>
 */
class BaseWap extends BaseAbstract {

    protected $md5Key = '';
    protected $apiURL = 'http://wappaygw.alipay.com/service/rest.htm';
    protected $mainParams = array(
        'service' => '',
        'format' => 'xml',
        'v' => '2.0',
        'partner' => '2088011574569325',
        'req_id' => '',
        'sec_id' => 'MD5',
        'sign' => '',
        '_input_charset' => 'utf-8'
    );
    protected $type = 'auth';
    protected $businessParams = array();
    private $params = array();

    protected function sign($params) {
        unset($params['sign']);
        ksort($params);
        $str = array();
        foreach ($params as $k => $v) {
            $str[] = $k . '=' . $v;
        }
        return md5(implode('&', $str) . $this->md5Key);
    }

    /**
     * 
     * @param string $type auth  or trade
     */
    protected function buildParams() {
        $req_data = array();
        foreach ($this->businessParams as $k => $v) {
            $v = trim($v);
            if ($v != '') {
                $req_data[] = '<' . $k . '>' . $v . '</' . $k . '>';
            }
        }

        
        $this->params = $this->mainParams;
        $tag = $this->type == 'auth' ? 'direct_trade_create_req' : 'auth_and_execute_req';

        $this->params['req_data'] = '<' . $tag . '>' . implode('', $req_data) . '</' . $tag . '>';

        foreach ($this->params as $k => $v) {
            if (trim($v) == '') {
                unset($this->params[$k]);
            }
        }
        $this->params['sign'] = $this->sign($this->params);
    }

    public function getRedirectURL() {
        $this->buildParams();
        $params = $this->params;
        $req_data = $params['req_data'];
        unset($params['req_data']);
        return $this->apiURL . '?' . http_build_query($params) . '&req_data=' . $req_data;
    }

    public function go() {
        $url = $this->getRedirectURL();
        if ($url != '') {
            header('Location: ' . $url);
        }
    }

}

?>
